<template>
  <van-nav-bar
    title="登录"
    left-text="返回"
    left-arrow
    @click-left="router.push('/')"
  />
  <div class="xl:w-[40%] xl:m-auto xl:mt-4">
    <van-form @submit="onSubmit" class="w-full">
      <van-cell-group inset>
        <van-field
          label-width="1.2rem"
          v-model="form.phone"
          name="手机号"
          label="手机号"
          placeholder="手机号"
          :rules="[{ required: true, message: '手机号不合法' }]"
        />
        <van-field
          label-width="1.2rem"
          v-model="form.password"
          type="password"
          name="密码"
          label="密码"
          placeholder="密码"
          :rules="[{ required: true, message: '请填写密码' }]"
        />
      </van-cell-group>
      <div
        class="flex justify-end text-base p-1 text-zinc-500"
        @click="handleReg"
      >
        立即注册
      </div>
      <div style="margin: 16px">
        <van-button
          :loading="btnLoading"
          loading-text="登录中..."
          round
          block
          type="primary"
          native-type="submit"
        >
          立即登录
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script setup>
import { ref } from "vue";
import { login } from "@/api/login.js";
import { Toast } from "vant";
import router from "@/router/index.js";
const onSubmit = () => {
  btnLoading.value = true;
  login(form.value).then((res) => {
    localStorage.setItem("userinfo", JSON.stringify(res));
    Toast.success("登录成功");
    btnLoading.value = false;
    setTimeout(() => {
      router.push("/");
    }, 1000);
  });
};
const handleReg = () => {
  router.push("/register");
};
const btnLoading = ref(false);
const form = ref({
  phone: "",
  password: "",
  type: 101,
});
</script>

<style lang="scss" scoped>
</style>